<template>
  <div class="login-container">
    <div style="padding: 26px 0;">
      <div class="logo-wrapper">
        <img src="../../assets/logo/logo-title.png" class="logo-title" alt />
        <span class="spliter"></span>
        <img src="../../assets/logo/title-logo.png" class="title-logo" alt />
      </div>
      <div class="main-wrapper">
        <img src="../../assets/background/background.jpg" alt />
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <div class="title">
            <h3>华普电力智能服务平台</h3>
            <span>Huapu Intelligent Service Platform</span>
          </div>

          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="用户名"
              name="username"
              type="text"
              tabindex="1"
              size="small"
              autocomplete="on"
            >
              <i slot="prefix" class="el-input__icon el-icon-user"></i>
            </el-input>
          </el-form-item>

          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                size="small"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              >
                <i slot="prefix" class="el-input__icon el-icon-lock"></i>
                <span slot="suffix" class="show-pwd el-input__icon" @click="showPwd">
                  <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </el-input>
            </el-form-item>
          </el-tooltip>
          <div>
            <el-checkbox v-model="isSave">下次自动登录</el-checkbox>
          </div>
          <el-button
            :loading="loading"
            type="primary"
            size="small"
            style="width:100%"
            @click.native.prevent="handleLogin"
          >登录</el-button>
        </el-form>
      </div>
      <div class="footer">
        <div>版权所有 © 华普电力有限公司 2019-2020。 保留一切权利。</div>
        <a href="http://www.beian.miit.gov.cn">渝ICP备17005035号</a>
      </div>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
// import SocialSign from "./components/SocialSignin";
import md5 from "md5";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6个字符"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: process.env.NODE_ENV === "production" ? "" : "郑碟飞",
        password: process.env.NODE_ENV === "production" ? "" : "huapu666"
      },
      // loginForm: {
      //   username: process.env.NODE_ENV === "production" ? "" : "",
      //   password: process.env.NODE_ENV === "production" ? "" : ""
      // },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      isSave: false
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && key >= "a" && key <= "z") ||
          (!shiftKey && key >= "A" && key <= "Z")
        ) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === "CapsLock" && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        const form = {
          username: this.loginForm.username,
          password: md5(this.loginForm.password),
          isSave: this.isSave
        };
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", form)
            .then(() => {
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery
              });
              this.loading = false;
            })
            .catch(e => {
              this.$message.error(e);
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #fff;
$light_gray: #fff;
$cursor: #fff;

.logo-wrapper {
  display: flex;
  align-items: center;
  margin-left: 20vw;
  margin-bottom: 1.8vw;
  min-height: 4.5vw;
  img {
    height: 4.5vw;
    width: auto;
  }
  .spliter {
    display: inline-block;
    height: 1.7vw;
    width: 1px;
    background: #808081;
    margin: 0 1.9vw;
  }
  .title-logo {
    height: 4vw;
  }
}
.main-wrapper {
  position: relative;
  min-height: 31.25vw;
  overflow: hidden;
  img {
    width: 100%;
    height: auto;
  }
  .el-form {
    position: absolute;
    min-width: 16vw;
    top: 50%;
    transform: translateY(-50%);
    margin-left: 20vw;
    background: $bg;
    padding: 1.2vw;
    border-radius: 6px;
    .title {
      text-align: center;
      margin-bottom: 20px;
      font-size: 14px;
      color: #1fa6e4;
      h3 {
        font-size: 24px;
        margin: 0;
        margin-bottom: 5px;
      }
    }
    .el-checkbox .el-checkbox__label {
      color: #999;
      margin-bottom: 16px;
    }
    .el-checkbox__input.is-checked .el-checkbox__inner {
      background: #1fa6e4;
      border-color: #1fa6e4;
    }
    .el-form-item {
      margin-bottom: 18px;
    }
    .el-button--primary {
      background: #1fa6e4;
      border: 0;
      font-size: 16px;
      &:hover {
        background: rgba($color: #1fa6e4, $alpha: 0.7);
        border-color: rgba($color: #1fa6e4, $alpha: 0.7);
      }
    }
  }
}

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  min-height: 100%;
  background: $bg;
  display: flex;
  align-items: center;
  .footer {
    font-size: 16px;
    text-align: center;
    margin-top: 1vw;
    line-height: 1.6;
    font-size: 14px;
    a:hover {
      color: rgba(31, 166, 228, 1);
    }
  }
  .el-input {
    input {
      background: transparent;
      -webkit-appearance: none;
      color: #333;
      caret-color: #c0c4cc;
      font-size: 16px;

      // &:-webkit-autofill {
      //   box-shadow: 0 0 0px 1000px $bg inset !important;
      //   -webkit-text-fill-color: $cursor !important;
      // }
    }
  }
  .el-form-item__content {
    line-height: 1;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;

  .show-pwd {
    position: absolute;
    right: 4px;
    top: 0px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
